import {call, put, take} from "redux-saga/effects";
import {FETCH_DATA, FETCH_RUNNING_DATA, SAVE_DATA, SAVE_RUNNING_DATA} from "./const";
import {queryDashboardData, queryRunningData} from "../../services/dashboard";
import {dashboardLoadingEndAction, dashboardLoadingStartAction} from "../loading/actionCreator";

function* getDashboardData(params) {
  yield put(dashboardLoadingStartAction());
  try {
    const payload = yield call(queryDashboardData, params);
    yield put({type: SAVE_DATA, payload: payload.data})
  } catch (e) {
    console.log(e);
  } finally {
    yield put(dashboardLoadingEndAction());
  }
}

function* getRunningData(params) {
  yield put(dashboardLoadingStartAction());
  try {
    const payload = yield call(queryRunningData, params);
    yield put({type: SAVE_RUNNING_DATA, payload: payload.data})
  } catch (e) {
    console.log(e);
  } finally {
    yield put(dashboardLoadingEndAction());
  }
}

export default function* saga() {
  const {payload} = yield take(FETCH_DATA);
  yield call(getDashboardData, payload);
  while (true) {
    const req = yield take(FETCH_RUNNING_DATA);
    yield call(getRunningData, req.payload);
  }
}
